package com.tbit.main.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author LMY
 * @create 2021-03-12 9:31
 * scheduled修改
 */
@EnableScheduling
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {

    @Autowired
    private TaskScheduler myThreadPoolTaskScheduler;


    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        //简单粗暴的方式直接指定
        //scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(20));

        //也可以自定义的线程池，方便线程的使用与维护，
        scheduledTaskRegistrar.setTaskScheduler(myThreadPoolTaskScheduler);
    }

    @Bean(name = "myThreadPoolTaskScheduler")
    public TaskScheduler getMyThreadPoolTaskScheduler() {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        //初始线程大小
        taskScheduler.setPoolSize(20);
        taskScheduler.setThreadNamePrefix("Haina-Scheduled-");
        taskScheduler.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //调度器shutdown被调用时等待当前被调度的任务完成
        taskScheduler.setWaitForTasksToCompleteOnShutdown(false);
        //等待时长
        taskScheduler.setAwaitTerminationSeconds(600);
        return taskScheduler;
    }
}
